package com.example.cinemasystemv2.controller;

import com.example.cinemasystemv2.entity.Movie;
import com.example.cinemasystemv2.entity.ScreeningRoom;
import com.example.cinemasystemv2.entity.Screening;
import com.example.cinemasystemv2.service.MovieService;
import com.example.cinemasystemv2.service.ScreeningRoomService;
import com.example.cinemasystemv2.service.ScreeningService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/debug")
public class DataCheckController {
    
    @Autowired
    private MovieService movieService;
    
    @Autowired
    private ScreeningRoomService screeningRoomService;
    
    @Autowired
    private ScreeningService screeningService;
    
    @GetMapping("/data-check")
    public ResponseEntity<Map<String, Object>> checkData() {
        Map<String, Object> response = new HashMap<>();
        
        try {
            // 获取所有电影
            List<Movie> allMovies = movieService.getAllMovies();
            List<Movie> activeMovies = allMovies.stream()
                .filter(movie -> movie.getStatus().equals("正在上映"))
                .collect(Collectors.toList());
            
            // 获取所有放映厅
            List<ScreeningRoom> rooms = screeningRoomService.getAllRooms();
            
            response.put("success", true);
            response.put("totalMovies", allMovies.size());
            response.put("activeMovies", activeMovies.size());
            response.put("totalRooms", rooms.size());
            
            // 详细信息
            response.put("movieDetails", allMovies.stream().map(m -> 
                Map.of("id", m.getId(), "title", m.getTitle(), "status", m.getStatus(), "duration", m.getDuration())
            ).collect(Collectors.toList()));
            
            response.put("roomDetails", rooms.stream().map(r -> 
                Map.of("id", r.getId(), "name", r.getName(), "seatCount", r.getSeatCount())
            ).collect(Collectors.toList()));
            
        } catch (Exception e) {
            response.put("success", false);
            response.put("error", e.getMessage());
            e.printStackTrace();
        }
        
        return ResponseEntity.ok(response);
    }
    
    @GetMapping("/auto-schedule-debug")
    public ResponseEntity<Map<String, Object>> debugAutoSchedule() {
        Map<String, Object> response = new HashMap<>();
        
        try {
            // 获取所有正在上映的电影
            List<Movie> movies = movieService.getAllMovies().stream()
                .filter(movie -> movie.getStatus().equals("正在上映"))
                .collect(Collectors.toList());
            
            // 获取所有放映厅
            List<ScreeningRoom> rooms = screeningRoomService.getAllRooms();
            
            response.put("activeMovies", movies.size());
            response.put("totalRooms", rooms.size());
            
            if (movies.isEmpty() || rooms.isEmpty()) {
                response.put("canSchedule", false);
                response.put("reason", "没有可用的电影或放映厅");
                return ResponseEntity.ok(response);
            }
            
            // 检查未来3天的时间段（使用与自动排片相同的逻辑）
            LocalDateTime startDate = LocalDateTime.now().plusDays(1).toLocalDate().atTime(9, 0);
            List<Map<String, Object>> timeSlots = new ArrayList<>();
            int availableSlots = 0;
            
            for (int day = 0; day < 3; day++) {
                LocalDateTime currentDate = startDate.plusDays(day);
                
                for (ScreeningRoom room : rooms) {
                    // 从每天9点开始为每个放映厅检查时间段
                    LocalDateTime currentTime = currentDate.withHour(9).withMinute(0);
                    LocalDateTime endOfDay = currentDate.withHour(22).withMinute(0);
                    
                    while (currentTime.isBefore(endOfDay)) {
                        Movie selectedMovie = movies.get((int) (Math.random() * movies.size())); // 随机选择电影
                        
                        // 创建测试场次
                        Screening testScreening = new Screening();
                        testScreening.setMovie(selectedMovie);
                        testScreening.setRoom(room);
                        testScreening.setStartTime(currentTime);
                        
                        // 检查是否有冲突
                        boolean hasConflict = screeningService.hasTimeConflict(testScreening);
                        
                        // 计算时间范围
                        LocalDateTime endTime = currentTime.plusMinutes(selectedMovie.getDuration());
                        LocalDateTime endTimeWithBuffer = endTime.plusMinutes(15);
                        
                        Map<String, Object> slotInfo = new HashMap<>();
                        slotInfo.put("date", currentTime.toLocalDate().toString());
                        slotInfo.put("time", currentTime.toLocalTime().toString());
                        slotInfo.put("room", room.getName());
                        slotInfo.put("movie", selectedMovie.getTitle());
                        slotInfo.put("duration", selectedMovie.getDuration());
                        slotInfo.put("endTime", endTime.toLocalTime().toString());
                        slotInfo.put("endTimeWithBuffer", endTimeWithBuffer.toLocalTime().toString());
                        slotInfo.put("hasConflict", hasConflict);
                        
                        if (!hasConflict) {
                            availableSlots++;
                        }
                        
                        timeSlots.add(slotInfo);
                        
                        // 计算下一个时间段：如果没有冲突，按电影时长+缓冲时间；如果有冲突，30分钟后重试
                        if (!hasConflict) {
                            currentTime = currentTime.plusMinutes(selectedMovie.getDuration() + 15);
                        } else {
                            currentTime = currentTime.plusMinutes(30);
                        }
                        
                        // 限制检查的时间段数量，避免无限循环
                        if (timeSlots.size() >= 50) {
                            break;
                        }
                    }
                    
                    if (timeSlots.size() >= 50) {
                        break;
                    }
                }
                
                if (timeSlots.size() >= 50) {
                    break;
                }
            }
            
            response.put("success", true);
            response.put("availableSlots", availableSlots);
            response.put("totalSlotsChecked", timeSlots.size());
            response.put("timeSlots", timeSlots.subList(0, Math.min(10, timeSlots.size()))); // 只返回前10个用于调试
            
        } catch (Exception e) {
            response.put("success", false);
            response.put("error", e.getMessage());
            e.printStackTrace();
        }
        
        return ResponseEntity.ok(response);
    }
    

    
    @GetMapping("/existing-screenings")
    public ResponseEntity<Map<String, Object>> checkExistingScreenings() {
        Map<String, Object> response = new HashMap<>();
        
        try {
            // 获取未来3天的场次
            LocalDateTime startDate = LocalDateTime.now().plusDays(1).toLocalDate().atTime(9, 0);
            LocalDateTime endDate = startDate.plusDays(3);
            
            List<Screening> existingScreenings = screeningService.getScreeningsByDateRange(startDate, endDate);
            
            response.put("success", true);
            response.put("totalExistingScreenings", existingScreenings.size());
            
            List<Map<String, Object>> screeningDetails = new ArrayList<>();
            for (Screening screening : existingScreenings) {
                Map<String, Object> detail = new HashMap<>();
                detail.put("id", screening.getId());
                detail.put("movie", screening.getMovie().getTitle());
                detail.put("room", screening.getRoom().getName());
                detail.put("startTime", screening.getStartTime().toString());
                detail.put("price", screening.getPrice());
                screeningDetails.add(detail);
            }
            
            response.put("screenings", screeningDetails);
            
        } catch (Exception e) {
            response.put("success", false);
            response.put("error", e.getMessage());
            e.printStackTrace();
        }
        
        return ResponseEntity.ok(response);
    }
}